#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>

using namespace std;

void NoneBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0) // fcntl失败
    {
        perror("fcntl err");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "SET " << fd << "  NONBLOCK DONE" << endl;
}

int main()
{
    char buffer[1024];
    NoneBlock(0);
    sleep(1);
    while (true)
    {
        printf("Please Enter #");
        fflush(stdout);

        ssize_t n = read(0, buffer, sizeof(buffer));

        if(n > 0)
        {
            buffer[n - 1] = 0;
            cout << "ECHO :" << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            //将fd设置成非阻塞，如果底层fd没有数据就绪，调用write/read/recv等 会以错误的形式返回
            // 为了区分是底层数据没有就绪还是程序出错
            //就以errno的形式来做区分

            if(errno == EWOULDBLOCK)
            {
                cout << "0 FD is not ready! try again !" << endl;
                sleep(1);
            }
            else
            {
                cerr << "read err, errno = "  <<errno <<  ", " << strerror(errno)<< endl;
                //break;
            }

        }
    }
    return 0;
}

